package com.kevis.zhunblog.admin.security.service;

import com.kevis.zhunblog.admin.security.entity.SecurityUser;
import com.kevis.zhunblog.core.entities.PowerMenuEntity;
import com.kevis.zhunblog.mapper.PowerMenuMapper;
import com.kevis.zhunblog.mapper.RolePowerMapper;
import com.kevis.zhunblog.service.PowerMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * 默认权限管理 DenyAllPermissionEvaluator 实现接口 PermissionEvaluator，里面直接返回fasle，所以需要我们自己定义类来具体实现
 * <p>
 * 前端根据传入参数来判断是否拥有权限
 * 方式一：
 * <div sec:authorize="hasPermission(#vars.ActionGUID,'Info_Insert')" >
 * <a href="javascript:void(0);" class="easyui-linkbutton" data-options="" onclick="Info_Insert()">添加11</a>
 * </div>
 * 方式二：
 * <script th:inline="javascript" type="text/javascript">
 * [# sec:authorize="hasPermission(#vars.ActionGUID,'Info_Update')"]
 * console.log('1111');
 * [/]
 * </script>
 * 参数说明：
 * #vars 表示要获取到的参数是什么，后面跟变量名 如 ActionGUID
 * Info_Insert 表示这个列表或按钮的 ActionName
 */
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {
    @Resource
    private RolePowerMapper rolePowerMapper;

    @Autowired
    private PowerMenuService powerMenuService;

    @Autowired
    private PowerMenuMapper powerMenuMapper;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        SecurityUser securityUserDetails = (SecurityUser) authentication.getPrincipal();
//        if (securityProperty.isSuperAuthOpen() && securityProperty.getSuperAdmin().equals(securityUserDetails.getUsername())) {
//            return true;
//        }
        String actionGuid = targetDomainObject.toString();
        String actionName = permission.toString();
        int roleId = securityUserDetails.getRoleId();
        List<String> strings = Collections.singletonList(actionName);
        String[] actionNames = new String[]{actionName};
        List<PowerMenuEntity> powerMenuEntityList = null;
        if (roleId == 9999) {
            powerMenuEntityList = powerMenuMapper.getListByMenuCode(actionGuid, actionNames);
        } else {
            powerMenuEntityList = powerMenuMapper.getListByMenuCodeAndRoleId(actionGuid, strings, roleId);
        }

        return powerMenuEntityList != null && powerMenuEntityList.size() > 0;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
